from db.repository.user_profile import UserProfileRepository
from services.llm import LLMService
from sqlalchemy.orm import Session
from typing import Dict, Any, Optional, List
import json
import time
from utils.logger import (
    emobot_logger,
    log_function_call,
    log_function_result,
    log_function_error,
)
from utils.performance_logger import (
    log_cache_operation,
    log_database_operation,
    log_api_call
)

logger = emobot_logger.get_logger()
from cache.redis import cache_service


class UserService:
    def __init__(self, db: Session):
        self.db = db
        self.user_profile_repo = UserProfileRepository(db)
        self.llm_service = LLMService()
        # 移除环境记忆仓储，现在只做实时场景识别

    def get_user_profile(self, user_id: str) -> Optional[Dict[str, Any]]:
        """Get user profile with caching"""
        start_time = time.time()

        # Try to get from cache first
        cache_key = f"user_profile:{user_id}"
        cache_start = time.time()
        cached_profile = cache_service.get(cache_key)
        cache_duration = (time.time() - cache_start) * 1000

        # 记录缓存查询操作
        log_cache_operation(
            operation="GET",
            key=cache_key,
            hit=cached_profile is not None,
            duration_ms=cache_duration
        )

        if cached_profile:
            return cached_profile

        # If not in cache, get from database
        db_start = time.time()
        user_profile = self.user_profile_repo.get_by_user_id(user_id)
        db_duration = (time.time() - db_start) * 1000

        # 记录数据库查询操作
        log_database_operation(
            operation="SELECT",
            table="user_profile",
            duration_ms=db_duration,
            record_count=1 if user_profile else 0
        )

        if user_profile:
            # Convert to dict and cache
            profile_dict = {
                "user_id": user_profile.user_id,
                "name": user_profile.name,
                "avatar": user_profile.avatar,
                "age": user_profile.age,
                "gender": user_profile.gender,
                "created_at": user_profile.created_at.isoformat()
                if user_profile.created_at
                else None,
                "updated_at": user_profile.updated_at.isoformat()
                if user_profile.updated_at
                else None,
            }

            # 缓存设置操作
            cache_set_start = time.time()
            cache_service.set(cache_key, profile_dict)
            cache_set_duration = (time.time() - cache_set_start) * 1000

            log_cache_operation(
                operation="SET",
                key=cache_key,
                duration_ms=cache_set_duration
            )

            return profile_dict
        return None


    def update_user_profile(
            self, user_id: str, user_data: Dict[str, Any]
    ) -> Optional[Dict[str, Any]]:
        """Update user profile"""
        updated_profile = self.user_profile_repo.update_by_user_id(user_id, user_data)
        if updated_profile:
            # Clear cache
            cache_key = f"user_profile:{user_id}"
            cache_service.delete(cache_key)
            # Convert to dict and return
            return {
                "user_id": updated_profile.user_id,
                "name": updated_profile.name,
                "avatar": updated_profile.avatar,
                "age": updated_profile.age,
                "gender": updated_profile.gender,
                "updated_at": updated_profile.updated_at.isoformat(),
            }
        return None

    # 云侧场景识别已禁用，以下方法已注释
    # async def _recognize_scene_with_vlm(
    #         self, image_url: str
    # ) -> Optional[Dict[str, Any]]:
    #     """使用VLM进行场景识别（简化版）"""
    #     try:
    #         # 生成场景识别提示词
    #         scene_prompt = self._generate_scene_recognition_prompt()
    #
    #         # 调用VLM API
    #         vlm_response = await self._call_vlm_for_scene_recognition(
    #             scene_prompt, image_url
    #         )
    #
    #         # 解析VLM响应
    #         scene_result = self._parse_scene_recognition_response(vlm_response)
    #
    #         return scene_result
    #
    #     except Exception as e:
    #         logger.error(f"VLM scene recognition error: {e}")
    #         return None

    # def _generate_scene_recognition_prompt(self) -> str:
    #     """生成包含场景模板的场景识别提示词"""
    #     ...已注释，云侧不再使用...
    
    # async def _call_vlm_for_scene_recognition(self, prompt: str, image_url: str) -> str:
    #     """调用LLM API进行场景识别 (VLM暂时被LLM替代)"""
    #     ...已注释，云侧不再使用...
    
    # def _parse_scene_recognition_response(self, vlm_response: str) -> Optional[Dict[str, Any]]:
    #     """解析LLM场景识别响应 (VLM暂时被LLM替代)"""
    #     ...已注释，云侧不再使用...
    
    # def _get_scene_category(self, scene_subcategory: str) -> str:
    #     """根据子场景名称获取主场景类别（简化版）"""
    #     ...已注释，云侧不再使用...
    pass  # UserService 类结束标记
